package com.yizisu.basemvvm.mvvm

import androidx.lifecycle.MutableLiveData


/**
 * 若红楼梦空，亦初心不变
 * 作者：kotle
 * 包名：com.yizisu.basemvvm.mvvm
 * 时间：2019/1/17 23:10
 * 描述：
 */
open class MvvmModel {

    /**
     * 同步viewModel的onCleared
     */
    fun onCleared() {
        callList.forEach {
            if (!it.isCanceled) {
                it.cancel()
            }
        }
        callList.clear()
        callListRetrofit.forEach {
            if (!it.isCanceled) {
                it.cancel()
            }
        }
        callListRetrofit.clear()
    }

    private val callList = mutableListOf<okhttp3.Call>()
    /**
     * 销毁的时候结束请求
     */
    fun okhttp3.Call.cancelOnDestroy(): okhttp3.Call {
        callList.add(this)
        return this
    }

    /**
     * 异步执行
     * 销毁的时候结束请求
     */
    fun okhttp3.Call.async(callback: okhttp3.Callback) {
        callList.add(this)
        enqueue(callback)
    }

    /**
     * 同步执行
     * 销毁的时候结束请求
     */
    fun okhttp3.Call.await(): okhttp3.Response {
        callList.add(this)
        return execute()
    }

    /**
     * retrofit
     */
    private val callListRetrofit = mutableListOf<retrofit2.Call<*>>()


    fun <BO> retrofit2.Call<BO>.cancelOnDestroy(): retrofit2.Call<BO> {
        callListRetrofit.add(this)
        return this
    }

    fun <BO> retrofit2.Call<BO>.async(callback: retrofit2.Callback<BO>) {
        callListRetrofit.add(this)
        enqueue(callback)
    }

    fun <BO> retrofit2.Call<BO>.await(): retrofit2.Response<BO> {
        callListRetrofit.add(this)
        return execute()
    }
}